/**
 * Created by zhangjinrui on 17/6/27.
 */

public class Solution106 {

    public static void main(String args[]) {
        Solution106 s = new Solution106();
        System.out.println(s.buildTree(new int[]{1, 2}, new int[]{2, 1}));
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length == 0) {
            return null;
        }
        if (inorder.length == 1) {
            return new TreeNode(inorder[0]);
        }

        int v = postorder[postorder.length - 1];
        int s = 0;

        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == v) {
                s = i;
                break;
            }
        }

        int[] inL = new int[s];
        int[] poL = new int[s];
        for (int i = 0; i < s; i++) {
            inL[i] = inorder[i];
            poL[i] = postorder[i];
        }

        int[] inR = new int[inorder.length - s - 1];
        int[] poR = new int[inorder.length - s - 1];
        for (int i = 0; i < inorder.length - s - 1; i++) {
            inR[i] = inorder[s + 1 + i];
            poR[i] = postorder[s + i];
        }
        TreeNode cur = new TreeNode(v);
        cur.left = buildTree(inL, poL);
        cur.right = buildTree(inR, poR);
        return cur;
    }

}
